#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:08
# @Author  : Tom_zc
# @FileName: parse_params.py
# @Software: PyCharm
import os
import sys
import json
import logging

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


def parse_payload_body():
    """parse the payload body"""
    payload = os.getenv("WEBHOOK_PAYLOAD")
    if not payload:
        logging.info("WEBHOOK_PAYLOAD must not be empty")
        sys.exit(-1)
    return json.loads(payload)


def parse_repo_info_by_webhook_payload(payload_body=None):
    """parse the owner repo branch pr from env WEBHOOK_PAYLOAD"""
    if not payload_body:
        payload_body = parse_payload_body()
    if payload_body["event_type"] == "note":
        owner = payload_body["merge_request"]["target"]["namespace"]
        repo = payload_body["merge_request"]["target"]["name"]
        branch = payload_body["merge_request"]["target_branch"]
        pr_number = payload_body['merge_request']['iid']
        url = payload_body['merge_request']['url']
    elif payload_body["event_type"] == "merge_request":
        owner = payload_body["object_attributes"]["target"]["namespace"]
        repo = payload_body["object_attributes"]["target"]["name"]
        branch = payload_body["object_attributes"]["target_branch"]
        pr_number = payload_body['object_attributes']['iid']
        url = payload_body['object_attributes']['url']
    else:
        raise RuntimeError("invalid event_type:{}".format(payload_body["event_type"]))
    return owner, repo, branch, pr_number, url
